package cn.com.support.authentication;

import java.util.Collection;
import java.util.Iterator;

import org.springframework.security.access.AccessDecisionManager;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;


/**
 * 
 * 授权访问控制
 * 
 * @since 2012-3-9 上午1:19:22
 * @version 1.0
 * @author Microbun
 */
public class AuteniticationAccessDecisionManager implements
		AccessDecisionManager {

	@Override
	public void decide(Authentication authentication, Object object,
			Collection<ConfigAttribute> configAttributes)
			throws AccessDeniedException, InsufficientAuthenticationException {
		// 如果访问的资源没有对应权限码，则直接通过
		if (configAttributes == null) {
			return;
		}

		// 遍历访问资源的权限码,并和用户认证码进行比较
		Iterator<ConfigAttribute> iterator = configAttributes.iterator();
		while (iterator.hasNext()) {
			// 拿到资源权限码
			ResourceAuthCode authCode = ResourceAuthCode.class
					.cast(iterator.next());
			if (authCode == null) {
				break;
			}

			for (GrantedAuthority ga : authentication.getAuthorities()) {
				// 拿资源权限码和用户认证码进行比较（authentication为用户认证码）
				if (AuthenticationUtil.containsResrc(authCode,
						ga.getAuthority())) {
					return;
				}
			}
		}

		// 如果没有匹配的，则表示没有权限
		throw new AccessDeniedException(" 没有权限访问！ ");
	}

	@Override
	public boolean supports(ConfigAttribute attribute) {
		return true;
	}

	@Override
	public boolean supports(Class<?> clazz) {
		return true;
	}

}
